package org.example.demo.service.userService.impl;

import org.example.demo.dto.OrderGenParam;
import org.example.mbg.mapper.*;
import org.example.mbg.model.*;
import org.example.demo.service.userService.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户订单service
 */
@Service
public class UserOrderServiceImpl implements UserOrderService {

    @Autowired
    private UserOrderMapper orderMapper;
    @Autowired
    private ProductByOrderMapper productByOrderMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderDetailMapper;

    @Override
    public String generateOrder(List<OrderGenParam> orderGenParam) {
        //获取用户余额
        Long userId = orderGenParam.get(0).getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        BigDecimal balance = user.getBalance();

        // 创建order详情
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setId(null);
        orderDetail.setCreateTime(new Date());
        orderDetail.setReceiverName(orderGenParam.get(0).getReceiverName());
        orderDetail.setReceiverPhone(orderGenParam.get(0).getReceiverPhone());
        orderDetail.setReceiverDetailAddress(orderGenParam.get(0).getReceiverLoc());
        orderDetailMapper.insertSelective(orderDetail);
        System.out.println(orderDetail.getId());
        // 创建order_product 关联表
        List<UserOrder> orders = new LinkedList<>();
        for (OrderGenParam genParam : orderGenParam) {
            UserOrder order = new UserOrder();
            order.setId(null);
            order.setOrderId(orderDetail.getId());
            order.setTotalAmount(genParam.getTotalAmount());
            order.setProductQuantity(genParam.getQuantity());
            order.setUserid(genParam.getUserId());
            order.setPaymentTime(new Date());
            order.setDeleteStatus(0);
            order.setStatus(0);
            order.setProductid(genParam.getProductId());
            order.setConfirmStatus(0);
            order.setDeleteStatus(0);
            orders.add(order);

            //更新余额
            balance = balance.subtract(genParam.getTotalAmount());
        }

        if (balance.compareTo(BigDecimal.ZERO) < 0)
            throw new RuntimeException("余额不足");

        orders.forEach(e -> {
            orderMapper.insertSelective(e);

            // 如果有相同的购物车条目，则删除
            ShopCartExample shopCartExample = new ShopCartExample();
            shopCartExample.createCriteria()
                    .andUserIdEqualTo(e.getUserid())
                    .andProductIdEqualTo(e.getProductid())
                    .andQuantityEqualTo(e.getProductQuantity());
            int s = shopCartMapper.deleteByExample(shopCartExample);
            System.out.println("结算清除购物车: " + s);
        });
        user.setBalance(balance);
        userMapper.updateByPrimaryKeySelective(user);
        return "ok";
    }


    //单件商品直接购买
    @Override
    public String buyOne(OrderGenParam genParam) {
        //获取用户余额
        Long userId = genParam.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        BigDecimal balance = user.getBalance();

        // 创建order详情
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setCreateTime(new Date());
        orderDetail.setId(null);
        orderDetail.setReceiverName(genParam.getReceiverName());
        orderDetail.setReceiverPhone(genParam.getReceiverPhone());
        orderDetail.setReceiverDetailAddress(genParam.getReceiverLoc());
        orderDetailMapper.insertSelective(orderDetail);

        UserOrder order = new UserOrder();
        order.setId(null);
        order.setTotalAmount(genParam.getTotalAmount());
        order.setProductQuantity(genParam.getQuantity());
        order.setUserid(genParam.getUserId());
        order.setPaymentTime(new Date());
        order.setDeleteStatus(0);
        order.setStatus(0);
        order.setProductid(genParam.getProductId());
        order.setConfirmStatus(0);
        order.setOrderId(orderDetail.getId());
        order.setDeleteStatus(0);

        //更新余额
        balance = balance.subtract(genParam.getTotalAmount());

        if (balance.compareTo(BigDecimal.ZERO) < 0)
            throw new RuntimeException("余额不足");

        user.setBalance(balance);
        orderMapper.insertSelective(order);
        userMapper.updateByPrimaryKeySelective(user);
        return "ok";
    }


    /*
     * 返回用户订单
     * */
    @Override
    public List<ProductByOrder> list(Long userId) {
        return productByOrderMapper.selectProductByUserId(userId)
                .stream().sorted(Comparator.comparing(ProductByOrder::getCreateTime)).collect(Collectors.toList());
    }

    @Override
    public ProductByOrder get(Long id, Long userId) {
        return productByOrderMapper.selectProductByUserId(userId).stream().filter(e -> e.getId().equals(id)).findFirst().orElse(null);
    }

    @Override
    public String receive(Long orderId) {
        UserOrder userOrder = new UserOrder();
        userOrder.setId(orderId);
        userOrder.setStatus(1);
        userOrder.setReceiveTime(new Date());
        return "ok " + orderMapper.updateByPrimaryKeySelective(userOrder);
    }

}
